////<!-- 指定车牌提醒配置 -->
import api from '../../../fetch/api'
import { deepCopyObjArray } from '../../../assets/js/help';

export default {
  data() {
    var validateCarNo = (rule, value, callback) => {
      value = $.trim(value);
      if (value === '') {
        callback(new Error('请填写车牌号码'));
      } else {
        if ((/^([冀豫云辽黑湘皖鲁苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼渝京津沪新京军空海北沈兰济南广成使领][a-zA-Z](([DF](?![a-zA-Z0-9]*[IO])[0-9]{4})|([0-9]{5}[DF])))|([冀豫云辽黑湘皖鲁苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼渝京津沪新京军空海北沈兰济南广成使领A-Z]{1}[a-zA-Z0-9]{5}[a-zA-Z0-9挂学警港澳]{1})|民航[a-zA-Z0-9]{5}$/).test(value)) {
          callback();
        } else {
          callback(new Error('车牌号码格式不正确'));
        }        
      }
    };
    return {
      selectedParkingLot: [], //选中的停车场数组
      selectedParkingLotStr: '', //选中的停车场str
      dialogVisibleForEmergency: false, //是否显示告警设置框
      emergencySetupId: '', //告警设置id
      cardNoIn: false, //指定车牌进场告警开关
      cardNoOut: false, //指定车牌离场告警开关
      pos_cardNoIn: false, //指定车牌进场告警开关-pos机
      pos_cardNoOut: false, //指定车牌离场告警开关-pos机
      delId: 0,
      isModify: false, // 新建/修改预订参数状态, 默认false为新建
      carNoVo: {
        "id": 0,
        "carCode": '',
        "mobile": '',
        parkIds: ''
      },
      rules: {
        carCode: [{
            required: true,
            min: 7,
            max: 20,
            message: '车牌号码须在 7 到 20 个字符',
            trigger: ['blur','change']
          },
          {
            validator: validateCarNo,
            trigger: ['blur','change']
          }
        ],
        mobile: [{
          validator(r, v, b) {
            if(v){
              /^1\d{10}$/.test(v) ? b() : b(new Error('手机格式不符合'));
            }
            b()
          },
          trigger: 'change'
        }],
        parkIds: [{
          required: true,
          message: '请选择停车场',
          trigger: 'change'
        }]
      }
    };
  },
  created() {
   
  },
  methods: {
    // 打开停车场树
    openSelectParkModal() {
      var _self = this;
      _self.toOpenModal('selectParkModal');
      this.initParkTree("ParkTree");
    },
    initParkTree(treeId) {
      var _self = this;
      let params = {
        parkSysType: 1
      }
      API.fetchGet('/parkingBaseData/getParkingBaseDataTree.do', params)
        .then(res => {
          if (res.data) {
            var nodes = res.data;
            var jsonStr = JSON.stringify(nodes);
            jsonStr = jsonStr.replace(/(\"isArea\"\:true\,)/g, '"isArea": true,"chkDisabled":true, "nocheck":true,');
            nodes = JSON.parse(jsonStr);
            var settings = {
              check: {
                enable: true,
                chkStyle: "checkbox",
                radioType: "all"
              },
              view: {
                showIcon: false,
                showLine: false,
              },
              callback: {
                onClick: function (event, treeId, treeNode) {
                  let treeObj = $.fn.zTree.getZTreeObj('ParkTree');
                  treeObj.checkNode(treeNode, true, false);
                  if (treeNode.isArea) {
                    return;
                  }
                },
              }
            };
            $.fn.zTree.destroy("ParkTree");
            var treeObj = $.fn.zTree.init($("#ParkTree"), settings, nodes);
            treeObj.expandAll(true);
            var allNodes = treeObj.getCheckedNodes(false)
            for(let i = 0; i<allNodes.length; i++){
              if(_self.carNoVo.parkIds.indexOf(allNodes[i].value)>-1){
                treeObj.checkNode(allNodes[i], true, false);
              }
            }
          } else {
            _self.showToast('暂时没有停车场可选', 2, 3000);
          }
        }, err => {})
    },
    // 停车场树-确认
    selectParkSure() {
      let self = this
      let treeObj = $.fn.zTree.getZTreeObj('ParkTree');
      let treeNodes = treeObj.getCheckedNodes(true); // 获取tree被勾选的节点
      if(!treeNodes || !treeNodes.length) {
        self.showToast('请至少选择一个停车场', 0, 1500)
        return;
      }
      self.carNoVo.parkIds = ''
      self.selectedParkingLot = []
      self.selectedParkingLotStr = ''
      let parkIds = []
      for(let i = 0; i<treeNodes.length; i++){
        parkIds.push(treeNodes[i].value)
        self.selectedParkingLot.push(treeNodes[i].name)
      }
      self.carNoVo.parkIds = parkIds.join(',')
      self.selectedParkingLotStr = self.selectedParkingLot.join('/')
      self.$refs.carNoForm.validateField('parkIds')
      self.closed('selectParkModal');
    },
    //打开告警设置框
    openEmergencySetup(){
      let self = this
      API.fetchGet('park/emergency/config/getCarlist.do',{}).then(res=>{
        let data = res.data
        self.emergencySetupId = data.id
        self.cardNoIn = data.carnoIn
        self.cardNoOut = data.carnoOut
        self.pos_cardNoIn = data.lmCarcodeIn
        self.pos_cardNoOut = data.lmCarcodeOut
      },err=>{})
      this.dialogVisibleForEmergency = true
    },
    //保存告警设置
    saveEmergencySetup(){
      let self = this
      let params = {};
      params.id = self.emergencySetupId
      params.carnoIn = self.cardNoIn==null ? false : self.cardNoIn
      params.carnoOut = self.cardNoOut==null ? false : self.cardNoOut
      params.lmCarcodeIn = self.pos_cardNoIn==null ? false : self.pos_cardNoIn
      params.lmCarcodeOut = self.pos_cardNoOut==null ? false : self.pos_cardNoOut
      API.fetchPost('park/emergency/config/updateCarlist.do',params).then(res=>{
        // console.log('res:',res)
        self.dialogVisibleForEmergency = false
      },err=>{})
    },
    getList() {
      let params = $.extend({}, this.searchParams, this.otherParams);
      this.getItemList(params);
    },
    //获取列表
    getItemList(aparams) {
      let self = this,
        params = {
          page: self.pageNumber,
          pageSize: self.pageSize
        };
      params = $.extend({}, params, aparams);
      self.tbodysInfo = []
      api.fetchGet('park/emergency/carNo/list.do', params)
        .then(res => {
          let data = res.data;
          self.tbodysInfo = data.rows;
          self.total = data.total;
        }, err => {});
    },
    showDeleteCarNo(id) { // 删除询问
      this.delId = id;
      this.toOpenModal("delConfirmTipModal");
    },
    submitCarNoForm() { // 点击新增/修改参数的确认按钮
      let self = this;
      self.$refs['carNoForm'].validate((valid) => {
        if (valid) { // 通过验证
          let carNoVo = self.carNoVo,
              id = carNoVo.id;

          var param = {
            carCode: carNoVo.carCode,
            parkIds: carNoVo.parkIds
          };
          if (id != 0) {
            param.id = id;
          }
          api.fetchPost('park/emergency/carNo/check.do', param).then(res => {
            if (res.status != 1) {
              self.showToast(res.message, 2);
            } else {
              self.postCarNoForm();
            }
          }, err => {});
        } else {
          return false;
        }
      });
    },
    convertToCarNoForm(vo) {
      var carNoForm = {
        "id": 0,
        "carCode": '',
        "mobile": '',
        parkIds: '',
      };
      for (var key in vo) {
        if (carNoForm.hasOwnProperty(key)) {
          carNoForm[key] = vo[key];
        }
      }
      return carNoForm;
    },
    postCarNoForm() { // 验证表单通过, 提交表单到后台
      let self = this;
      var carNoForm = self.convertToCarNoForm(self.carNoVo);
      if (carNoForm.id == 0) {
        // 新增
        api.fetchPost('park/emergency/carNo/create.do', carNoForm)
          .then(res => {
            if (res.status == 1) {
              self.showToast('保存成功', 1);
              self.getList();
              self.closed('carNoModal');
            }
          }, err => {});
      } else {
        // 更新
        api.fetchPost('park/emergency/carNo/update.do', carNoForm)
          .then(res => {
            if (res.status == 1) {
              self.showToast('保存成功', 1);
              self.getList();
              self.closed('carNoModal');
            }
          }, err => {});
      }
    },
    addCarNo() {
      this.carNoVo = {
        "id": 0,
        "carCode": '',
        "mobile": '',
        parkIds: ''
      };
      this.selectedParkingLot = []
      this.selectedParkingLotStr = ''
      this.isModify = false;
      this.toOpenModal('carNoModal');
    },
    updateCarNo(rowData) {
      let self = this;
      api.fetchGet('park/emergency/carNo/getById.do', {
          id: rowData.id
        })
        .then(res => {
          if (res.status == 1) {
            let data = res.data
            self.carNoVo = {
              id: data.id,
              carCode: data.carCode,
              mobile: data.mobile,
              parkIds: ''
            };
            if(Array.isArray(data.parkIdList) && data.parkIdList.length){
              self.carNoVo.parkIds = data.parkIdList.join(',')
            }
            self.selectedParkingLotStr = rowData.parkNameList.join('/')
            self.selectedParkingLot = deepCopyObjArray(rowData.parkNameList)
            self.isModify = true;
            self.toOpenModal('carNoModal');
          } else {
            self.showToast(res.message, 2);
          }
        }, err => {});
    },
    deleteCarNo() {
      let self = this;
      api.fetchPost('park/emergency/carNo/delete.do', {
          id: self.delId
        })
        .then(res => {
          if (res.status == 1) {
            self.getList();
            self.closed('delConfirmTipModal', 1);
            self.showToast('删除成功', 1);
          } else {
            self.showToast('删除失败', 2);
          }
        }, err => {});
    },
    exportData() {
      let self = this;
      let theadsArr = []
      for(let i = 0; i<self.theadsInfo.length; i++){
        if(self.theadsInfo[i].checked){
          theadsArr.push(self.theadsInfo[i].prop)
        }
      }
      let params = {
        meterList: theadsArr.join(',')
      };
      params = $.extend({}, params, this.searchParams, this.otherParams);
      self.showDialog("确认导出该报表?", '', function () {
        self.toExportAsync('park/emergency/carNo/export.do', params);
      });
    }
  }
}
